﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.Office.Server.Search.Administration;
using Microsoft.Office.Server;

namespace SearchAdminToolkit.UI.Controls
{
    /// <summary>
    /// Defines a class for working with <see cref="ManagedProperty"/> objects in SharePoint.
    /// </summary>
    class PropertyManager
    {

        /// <summary>
        /// Finds <see cref="ManagedProperty"/> objects by name.
        /// </summary>
        /// <param name="name"></param>
        /// <returns></returns>
        public static List<ManagedProperty> FindByName(string name)
        {
            ManagedPropertyCollection properties = GetSspManagedProperties();
            return (from ManagedProperty p in properties where p.Name.ToUpper().Contains(name.ToUpper()) orderby p.Name ascending select p).ToList<ManagedProperty>();
        }

        /// <summary>
        /// Finds a <see cref="ManagedProperty"/> object.
        /// </summary>
        /// <param name="managedPropName"></param>
        /// <returns></returns>
        public static ManagedProperty Find(string managedPropName)
        {
            ManagedPropertyCollection properties = GetSspManagedProperties();
            return properties[managedPropName];
        }

        /// <summary>
        /// Gets the Managed Properties for the current SSP.
        /// </summary>
        /// <returns></returns>
        private static ManagedPropertyCollection GetSspManagedProperties()
        {
            Schema ssp = new Schema(SearchContext.GetContext(ServerContext.Default));

            return ssp.AllManagedProperties;
        }

        /// <summary>
        /// Updates an existing <see cref="ManagedProperty"/>.
        /// </summary>
        /// <param name="managedPropName"></param>
        /// <param name="weight"></param>
        /// <param name="lengthNormalization"></param>
        public static void Update(string managedPropName, float weight, float lengthNormalization)
        {
            ManagedProperty prop = Find(managedPropName);
            
            prop.Weight = weight;
            prop.LengthNormalization = lengthNormalization;

            prop.Update();
        }

    }
}
